package com.yys.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.yys.common.constant.ProductConstant;
import com.yys.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.yys.gulimall.product.dao.AttrGroupDao;
import com.yys.gulimall.product.dao.CategoryDao;
import com.yys.gulimall.product.entity.*;
import com.yys.gulimall.product.service.CategoryService;
import com.yys.gulimall.product.vo.AttrGroupRelationVo;
import com.yys.gulimall.product.vo.AttrRespAo;
import com.yys.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yys.common.utils.PageUtils;
import com.yys.common.utils.Query;

import com.yys.gulimall.product.dao.AttrDao;
import com.yys.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);

        //基本类型才需要关联分组, 销售属性没有分组
        // 保存关联关系
        // 还要判断group不为空
        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPEBASE.getCode()
                && ObjectUtils.isNotNull(attr.getAttrGroupId())) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("attr_type","base".equalsIgnoreCase(attrType)?
                ProductConstant.AttrEnum.ATTR_TYPEBASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId != 0) {
            wrapper.eq("catelog_id",catelogId);
        }
        String key = (String) params.get("key");

        if(!StringUtils.isEmpty(key)) {
            wrapper.and(attr -> attr
                    .eq("attr_id",key)
                    .or()
                    .like("attr_name",key));
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespAo> respAoList = records.stream().map(attrEntity -> {
            AttrRespAo attrRespAo = new AttrRespAo();
            BeanUtils.copyProperties(attrEntity, attrRespAo);

            if("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId())
                );
                if (ObjectUtils.isNotNull(relationEntity)) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespAo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (ObjectUtils.isNotNull(categoryEntity)) {
                attrRespAo.setCatelogName(categoryEntity.getName());
            }
            return attrRespAo;
        }).collect(Collectors.toList());

        pageUtils.setList(respAoList);
        return pageUtils;
    }

    @Override
    public AttrRespAo getAttrInfo(Long attrId) {
        AttrRespAo attrRespAo = new AttrRespAo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespAo);

        //只有基本属性才需要分组
        //分组信息
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPEBASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId())
            );
            if(ObjectUtils.isNotNull(relationEntity) && ObjectUtils.isNotNull(relationEntity.getAttrGroupId())) {
                attrRespAo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if(ObjectUtils.isNotNull(attrGroupEntity)) {
                    attrRespAo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespAo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(ObjectUtils.isNotNull(categoryEntity)) {
            attrRespAo.setCatelogName(categoryEntity.getName());
        }
        return attrRespAo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPEBASE.getCode()) {
            //修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            // 判断此次操作是修改还是新增
            Integer count = attrAttrgroupRelationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId())
            );

            if(count > 0) {
                // 修改
                attrAttrgroupRelationDao.update(relationEntity,
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId())
                );
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entityList = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attrgroupId)
        );
        if(ObjectUtils.isEmpty(entityList)) {
            //TODO 是否返回空数组?
            return new ArrayList<>(0);
        }
        List<Long> attrIds = entityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        return this.listByIds(attrIds);
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo... vos) {
//        attrAttrgroupRelationDao.delete(
//                new QueryWrapper<AttrAttrgroupRelationEntity>()
//                        .eq("attr_id",1L)
//                .eq("attr_group_id",1L)
//        );
        //批量删除
        List<AttrAttrgroupRelationEntity> relationEntityList = Arrays.asList(vos).stream().map(vo -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(relationEntityList);
    }

    @Override
    public PageUtils getNoRelationAttr(String attrgroupId, Map<String, Object> params) {
        // 当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 只能关联别的分组没有引用的属性
        // 找到当前分类的其他分组,找到分组的属性,排除掉这些
        List<AttrGroupEntity> attrGroupEntityList = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>()
                        .eq("catelog_id", catelogId)
        );

        List<Long> collect = attrGroupEntityList.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());

        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", collect)
        );
        List<Long> attrIds = relationEntityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                //只查询基本属性
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPEBASE.getCode());

        if(ObjectUtils.isNotEmpty(attrIds)) {
            wrapper.notIn("attr_id", attrIds);
        }

        String key = (String) params.get("key");

        if(!StringUtils.isEmpty(key)) {
            wrapper.and((w)-> w.eq("attr_id",key).or().like("attr_name",key));
        }


        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public List<Long> getSearchAttrs(List<Long> attrIds) {

        /**
         * select attr_id from pms_attr where attr_id in () and search_type = 1
         * */
        return this.baseMapper.getSearchAttrs(attrIds);

    }


}